package cn.fancy.sdk.service.utils;

import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

public class QdJSLinker {
	
	private static String TAG = QdJSLinker.class.getSimpleName();
	private HashMap<String, Integer> JSM;
	private static Context mContext;
	
	public QdJSLinker(Context context) 
	{ 
		initLinker(context);
	}
	
	private void initLinker(Context context)
	{
		mContext = context;
		JSM = new HashMap<String, Integer>();
		JSM.put("toastMessage", 1);
		JSM.put("makeCall", 2);
		JSM.put("startDialog", 3);
		JSM.put("mkqqDialog", 4);
	}
	
	/* The following are functions used by JS */ // ==================================
	private void toastMessage(String message) 
	{
		QdMakeLog.d(TAG, "H5 will toast a message");
        Toast.makeText(mContext, message, Toast.LENGTH_LONG).show();
    }
	
	private void startQQDialog(String qnumber, boolean isMKQQ)
	{
		QdMakeLog.d(TAG, "H5 will start normal qq dialog");
		boolean canOpenQQ = false;
		final PackageManager packageManager = mContext.getPackageManager(); 
	    List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
	    if (pinfo != null) {
	      for (int i = 0; i < pinfo.size(); i++) {
	        String pn = pinfo.get(i).packageName;
	        if (pn.equals("com.tencent.mobileqq")) {
	        	canOpenQQ = true;
	        	break;
	        }
	      } 
	    } 
	     if(canOpenQQ == true) {
	    	 if(isMKQQ == true) {
	    		 String qqurl = "http://wpa.b.qq.com/cgi/wpa.php?ln=2&uin=" + qnumber;
	    		 mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(qqurl)));
	    	 } else {
		    	 String qqurl = "mqqwpa://im/chat?chat_type=wpa&uin=" + qnumber;
		    	 mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(qqurl)));
	    	 }
	     } else {
	    	 if(isMKQQ == true) {
	    		 String qqurl = "http://crm2.qq.com/page/portalpage/wpa.php?aty=1&a=0&curl=&ty=1&uin=" + qnumber;
	    		 mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(qqurl)));
	    	 } else {
	    		 Toast.makeText(mContext, "未安装手机QQ，无法打开会话", Toast.LENGTH_SHORT).show();
	    	 }
	     }
	}
	
	private void makeCall(String pnumber)
	{
		QdMakeLog.d(TAG, "H5 will makeCall");
		mContext.startActivity(new Intent(Intent.ACTION_DIAL,Uri.parse("tel:" + pnumber)));
	}
	
}
